package course.web;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import lombok.extern.slf4j.Slf4j;
import course.domain.Course;
import course.domain.Personal;
import course.domain.CourseAttribute;
import course.domain.CourseAttribute.Type;

@SessionAttributes(value="selection")
@Slf4j
@Controller
@RequestMapping("/selection")
public class SelectionController {
	@ModelAttribute
	public void addCourseAttributesToModel(Model model) {
		List<CourseAttribute> CourseAttributes = Arrays.asList(
				  new CourseAttribute("1","计算机基础", "c1-202", Type.COMPUTER),
				  new CourseAttribute("2", "软件工程","c2-303" ,Type.COMPUTER),
				  new CourseAttribute("3", "计算机英语","c5-201" ,Type.ENGLISH),
				  new CourseAttribute("4", "大学英语","c5-202" ,Type.ENGLISH),
				  new CourseAttribute("5", "离散数学", "d1-101",Type.MATH),
				  new CourseAttribute("6", "高等数学", "d2-101",Type.MATH)
				 
				);
		Type[] types = CourseAttribute.Type.values();
		for (Type type : types) {
		  model.addAttribute(type.toString().toLowerCase(),
		      filterByType(CourseAttributes, type));//��KEY-VALUE��ʽ��������ӵ�model
		}
	}
	@GetMapping
	public String showselectionForm(Model model) {
		model.addAttribute("selection",new Course());
		return "selection";
	}
	@PostMapping
	public String  processCourse(@Valid @ModelAttribute("selection") Course course,Model model, Errors errors) {
		if(errors.hasErrors()) {
			return "selection";
		}
		log.info("已选课程: " + course);
		return "redirect:/result";
	}
	
	 private List<CourseAttribute> filterByType(
		      List<CourseAttribute> CourseAttributes, Type type) {
		    return CourseAttributes
		              .stream()
		              .filter(x -> x.getType().equals(type))
		              .collect(Collectors.toList());
		  }
	


}